package simple

import (
	"fmt"
	"net"
	"net/http"
)

func StartV2() {
	//s := &HttpsServerV2{
	//	ServerV2: &HttpsServerV2{},
	//}
	s := &HttpServerV2{}
	_ = s.Start(":8001")
}

type ServerV2 interface {
	http.Handler
	Start(addr string) error
}

type HttpServerV2 struct {
}

func (m *HttpServerV2) Start(addr string) error {
	//// 阻塞，启动前可以加hook
	//return http.ListenAndServe(addr, m)

	// 非阻塞，启动前加hook
	fmt.Println("Starting...")
	listener, err := net.Listen("tcp", addr)
	if err != nil {
		return err
	}
	// 启动后加hook
	fmt.Println("Started")
	return http.Serve(listener, m)

}
func (m *HttpServerV2) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
	_, _ = writer.Write([]byte("hello, world"))
}

type HttpsServerV2 struct {
	ServerV2
	key  string
	cert string
}

func (s *HttpsServerV2) Start(addr string) error {
	return http.ListenAndServeTLS(addr, s.cert, s.key, s)
}
